<template>
  <el-dialog modal-class="email-rule-modal" model-value="true" width="600px" title="规则设置">
    <div class="email-rule-dialog">
      <div class="flex">
        <span style="line-height: 32px;">邮箱账户：</span>
        <el-select
          v-model="currentAccout"
          class="m-2"
          placeholder="Select"
          size="small"
          style="width: 358px"
        >
          <el-option
            v-for="item in accountList"
            :key="item.id"
            :label="item.account"
            :value="item.account"
          />
        </el-select>
      </div>
      <div class="email-rule-wrap">
        <div class="email-rule-table-head">
          <div class="flex-row">
            <!-- <div class="flex-row-item">
              <span class="font12">状态</span>
            </div> -->
            <div class="flex-row-item">
              <span class="font12">条件</span>
            </div>
            <div class="flex-row-item">
              <span class="font12">执行</span>
            </div>
            <div class="flex-row-item">
              <span class="font12">操作</span>
            </div>
          </div>
        </div>
        <div v-for="(row, index) in emailRuleList" :key="index">
          <div class="email-rule-table-item">
            <div class="flex-row">
              <!-- <div class="flex-row-item">
                <el-checkbox @change="changeEmailStatus(i)" :false-label="1" :true-label="0" v-model="i.status" size="large" />
              </div> -->
              <div class="flex-row-item">
                <span class="font12" v-html="row.condition"></span>
              </div>
              <div class="flex-row-item ellipsis">
                <span class="font12">{{ row.operation }}</span>
              </div>
              <div class="flex-row-item">
                <el-button v-if="row.status === 1" @click="handleChangeStatus(row)" size="small" link>启用</el-button>
                <el-button v-else @click="handleChangeStatus(row)" size="small" link>停用</el-button>
                <el-button @click="ediRule(row.id)" size="small" link>编辑</el-button>
                <el-button @click="deleteEmailItem(row.id)" size="small" link>删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-wrap">
        <!-- <el-button-group>
          <el-button @click="addEmailItem" size="small">
            <i class="iconfont icon-plus" />
          </el-button>
          <el-button @click="deleteEmailItem" :disabled="!currentRuleId" size="small">
            <i class="iconfont icon-minus" />
          </el-button>
        </el-button-group> -->
        <el-button @click="addEmailItem" size="small">
          新建规则
        </el-button>
      </div>
    </div>
    <rule-dialog ref="ruleDialogRef" :id="currentRuleId" @close="handlerClose" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref  } from 'vue';
import { storeToRefs } from 'pinia';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';
import api from "/@/api/email/index"

const RuleDialog = defineAsyncComponent(() => import('./ruleDialog.vue'));
const emailRuleList = ref<any>([])
const currentRuleId = ref<string>('');
const stores = useEmail(pinia);
const { curAccount, accountList } = storeToRefs(stores);

// const folder = ref('');
// const options = ref([]);
const ruleDialogRef = ref()
const currentAccout = ref<any>(curAccount.value);
const ediRule = (id: string) => {
  currentRuleId.value = id;
  ruleDialogRef.value.showDialog = true
};

const formatCondition = (item: any) => {
    let strList: string[] = []
    // addresser 发件人
    // recipients 收件人
    // theme 主题
    if(item.addressers) {
        const str = item.addressers.reduce((str: string, item: any) => {
            if (str) {
                str += item.connect === 'and' ? '并且' : '或';
            } else {
                str = '发件人';
            }
            str += (item.type ? '包含' : '不包含') + item.keyword;
            return str;
        }, '');
        strList.push(str);
    }

    if(item.recipientss) {
        const str = item.recipientss.reduce((str: string, item: any) => {
            if (str) {
                str += item.connect === 'and' ? '并且' : '或';
            } else {
                str = '收件人';
            }
            str += (item.type ? '包含' : '不包含') + item.keyword;
            return str;
        }, '');
        strList.push(str);
    }

    if(item.themes) {
        const str = item.recipientss.reduce((str: string, item: any) => {
            if (str) {
                str += item.connect === 'and' ? '并且' : '或';
            } else {
                str = '主题';
            }
            str += (item.type ? '包含' : '不包含') + item.keyword;
            return str;
        }, '');
        strList.push(str);
    }
    return strList.join('<br />');
}

const formatOperation =  (item: any) => {
    return `移动到${item.folder}`
};

const handleChangeStatus = (row:any) => {
    api.rule.changeStatus({
        id: row.id,
        status: row.status === 1 ? 0 : 1
    }).then(() => {
        ElMessage.success('状态切换成功');
        getList();
    });
}

const addEmailItem = () => {
    currentRuleId.value = '';
    ruleDialogRef.value.showDialog = true
};

/**
 * 删除邮箱
 */
const deleteEmailItem = (id: string) => {
    ElMessageBox.confirm('此操作将删除该规则，是否继续？', '提示', {
        confirmButtonText: '清空',
        cancelButtonText: '取消',
    })
    .then(() => {
    api.rule.deleteItem(id).then((res: any) => {
        ElMessage.success('删除成功');
        getList();
    });
    })
    .catch(() => {});
}

const getList = async () => {
    api.rule.getList(currentAccout.value).then((res: any) => {
        emailRuleList.value = res.data.map((item: any) => {
            return {
                ...item,
                condition: formatCondition(item),
                operation: formatOperation(item),
            };
        });
    }); 
};

const handlerClose = (refresh: boolean) => {
  if (refresh) {
    getList();
  }
  ruleDialogRef.value.showDialog = false
}

// getFolderList();
getList();
</script>
<style lang="scss" scoped>
.email-rule-dialog {
  .footer-wrap {
    text-align: right;
  }
  .email-rule-wrap {
    margin: 12px 0;
    border: 1px solid #dbdddd;
    height: 300px;
  }
}
// .btn-wrap {
//   margin-left: 8px;
//   display: flex;
//   .minus-btn {
//     margin-left: 0px;
//   }
//   .plus-btn,
//   .minus-btn {
//     padding: 6px 8px;
//     :deep(.el-icon) {
//       margin-right: 0;
//     }
    
//   }
// }

.el-input {
  height: 32px;
}
:v-deep .el-cascader {
  height: 32px;
  line-height: 32px;
  .el-input {
    --el-input-inner-height: 32px;
  }
}
:deep(.el-select__wrapper) {
  height: 32px;
}

.border {
  border: 1px solid #dbdddd;
}

.bold {
  font-weight: bold;
}

.tips {
  color: #000000;
}

.active {
  background: linear-gradient(#7d93a8, #6d7e8e);
  color: #fff;
}
.flex-row {
  padding: 2px 8px;
  .flex-row-item:nth-child(1) {
    width: 300px;
    text-align: left;
  }
  .flex-row-item:nth-child(2) {
    width: 120px;
    
  }
  .flex-row-item:nth-child(3) {
    width: 120px;
  }
}
.email-rule-table-head {
  border-bottom: 1px solid #dbdddd;
  background: #efefef;
}
</style>
<style lang="scss">
.email-rule-modal .el-dialog {
  padding-bottom: 20px;
}
</style>